import React from 'react'
import {View, Image} from '@tarojs/components'
import {AtButton} from 'taro-ui'
import Taro from "@tarojs/taro";
import {getEnv} from "../../env";
import userStore, {UserInfo} from "../../store/userStore"
import './index.scss'

export default () => {
  async function login(res) {
    const rawData = res.detail.rawData;
    const {code} = await Taro.login();
    Taro.showLoading({mask:true,title:"加载中"});
    const result = await Taro.request({
      url: `${getEnv().baseUrl}/user/login`,
      data: {code, rawData},
      method: "POST"
    }).finally(() => Taro.hideLoading())
    const userInfo: UserInfo = {
      ...JSON.parse(rawData),
      token: result.data.token,
      isLogin: result.data.isSetMobile === "1",
      openId: result.data.openId
    }
    userStore.dispatch("set", userInfo)
    // 跳转绑定手机
    if (!userInfo.isLogin) {
      Taro.navigateTo({
        url: "/pages/bindMobilePhone/index?openId=" + userInfo.openId
      })
    } else {
      Taro.showToast({title: "登录成功", icon: "success"})
      Taro.reLaunch({
        url: "/pages/index/index"
      })
    }
  }

  return <View className='wing-blank'>
    <View>
      <View className='container'>
        <Image
          style='width: 120px;height: 120px;'
          src='https://aev.xiaotang365.cn/256-256.png'
        />
      </View>
      <View>
        <AtButton type='primary' openType='getUserInfo' onGetUserInfo={login}>授权登录</AtButton>
      </View>
      <View style={{marginTop: "10px"}}>
        <AtButton type='secondary' onClick={() => Taro.navigateBack()}>取消</AtButton>
      </View>
    </View>
  </View>
}
